<?php

class Ext_Avatar_Save_Adapter_Fastdfs
{
    protected $_datas    = array();
    protected $_messages = array();
    
    const RENAME_IMAGE_FAILED = 'renameImageFailed';
    protected $_messageTemplates = array(
        self::RENAME_IMAGE_FAILED => "Rename image failed.",
    );
    protected $_messager;
    
    public function __construct()
    {
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }

    public function save($file)
    {
        $result = array(
            'code'     => Ext_Image_Save_Result::FAILURE,
            'data'     => '',
            'messages' => array(),
        );
        
        $sourceMd5sum = md5_file($file);
        $image = App_Model_DbTable_Image::getInstance()->getRowByMd5sum($sourceMd5sum);
        if($image){
            $imageId = $image['id'];
            $result['code'] = Ext_Avatar_Save_Result::SUCCESS;
            $result['data'] = $imageId;
            return new Ext_Avatar_Save_Result($result['code'], $result['data'], $result['messages']);
        }
        
        $insertAvatarRow = array();
        $resizer = new Ext_Avatar_Save_Resize($file);
        $config = Ext_Config::getInstance()->getConfig('image');
        foreach($config->avatar->size as $sizeName=>$size){
            $resizeFile = $resizer->resize($sizeName);
            $resizeMd5sum = md5_file($resizeFile);
            
            $imageFastdfs = App_Model_DbTable_Image_Fastdfs::getInstance()->getRowByMd5sum($resizeMd5sum);
            if($imageFastdfs){
                $resizeImageId = $imageFastdfs['id'];
                $insertAvatarRow[$sizeName] = $resizeImageId;
                continue;
            }
            
            $file_info = Ext_Fastdfs::getInstance()->upload($resizeFile);
            $group  = $file_info['group_name'];
            $fileId = $file_info['filename'];
            $row = array(
                'md5sum'     => $resizeMd5sum,
                'group'      => $group,
                'fileId'     => $fileId,
                'createTime' => time(),
            );
            $resizeImageId = App_Model_DbTable_Image_Fastdfs::getInstance()->addNew($row);
            $insertAvatarRow[$sizeName] = $resizeImageId;
        }
        $avatarId = App_Model_DbTable_Avatar::getInstance()->addNew($insertAvatarRow);

        $result['code'] = Ext_Avatar_Save_Result::SUCCESS;
        $result['data'] = $avatarId;
        return new Ext_Avatar_Save_Result($result['code'], $result['data'], $result['messages']);

    }
}
